﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using RookieLibSharp.Database;
using RookieLibSharp.Configuration;
using RookieLibSharp.Progress;
namespace BirthdayRemainder.Forms
{
    public partial class FrmImportData : Form
    {
        private DataTable dtExample;
        private const int BASE_COL_CNT = 5;
        private const int COL_NAME = 1;
        private const int COL_BIRTH = 2;
        private const int COL_SOLAR = 3;
        private const int COL_PHONE = 4;
        public bool IsImportErr { get; set; }
        public bool IsImportData { get; set; }
        private const int THD_ID = 0;
        public FrmImportData()
        {
            InitializeComponent();
        }
        private void FrmImportData_Load(object sender, EventArgs e)
        {
            this.LabTableName.Visible = false;
            this.cbbShtName.Visible = false;
            InitExampleDT();
            //this.tbTableName.Text = Cfg.ReadString(PubVal.SFT_CFG, PubVal.SFT_CFG_IMPORT_SHT_NAME);
            IsImportErr = false;
            IsImportData = false;
        }
        /// <summary>
        /// 导入txt数据
        /// </summary>
        /// <param name="path"></param>
        private void ImportTextData(string path)
        {
            using (FileStream FS = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                StreamReader sr = new StreamReader(FS, Encoding.Default);
                string str;
                string[] ArrStr;
                ProgressManager.Init(THD_ID, "导入数据", FS.Length);
                while (null != (str = sr.ReadLine()))
                {
                    str = str.Replace(";", ",");
                    str = str.Replace("，", ",");
                    ArrStr = str.Split(',');
                    if (ArrStr.Length >= BASE_COL_CNT)
                    {
                        if (Funcs.IsDate(ArrStr[COL_BIRTH]))
                        {
                            PersonInfo info = new PersonInfo();
                            info.Name = ArrStr[COL_NAME];
                            info.Birthday = Convert.ToDateTime(ArrStr[COL_BIRTH]).ToString(GlobalValue.STR_DATE_TIME_FORMAT);
                            info.Phone = ArrStr[COL_PHONE];
                            info.IsLunar = (ArrStr[COL_SOLAR] == "阴历");
                            SftMgr.DbUpdateRecord(info);
                        }
                    }
                    ProgressManager.UpdateVale(THD_ID, str.Length);
                }
                sr.Close();
                FS.Close();
            }
        }
        /// <summary>
        /// 导入excel数据
        /// </summary>
        /// <param name="path"></param>
        /// <param name="shtName"></param>
        private void ImportExcelData(string path,string shtName)
        {
            DatabaseMgr database = new DatabaseMgr(DatabaseFileType.Excel, path);
            DataTable dtInfo = database.GetAllData(shtName);
            if (dtInfo == null)
            {
                Msg("导入数据失败");
                IsImportErr = true;
                return;
            }
            if (dtInfo.Columns.Count >= BASE_COL_CNT)
            {
                ProgressManager.Init(THD_ID,"导入数据",dtInfo.Rows.Count);
                for (int rowIdx = 0; rowIdx < dtInfo.Rows.Count;rowIdx++ )
                {
                    if (Funcs.IsDate(dtInfo.Rows[rowIdx][COL_BIRTH].ToString()))
                    {
                        PersonInfo info = new PersonInfo();
                        info.Name = dtInfo.Rows[rowIdx][COL_NAME].ToString();
                        info.Birthday = Convert.ToDateTime(dtInfo.Rows[rowIdx][COL_BIRTH]).ToString(GlobalValue.STR_DATE_TIME_FORMAT);
                        info.IsLunar = (dtInfo.Rows[rowIdx][COL_SOLAR].ToString() == "阴历");
                        info.Phone = dtInfo.Rows[rowIdx][COL_PHONE].ToString();
                         SftMgr.DbUpdateRecord(info);
                    }
                    ProgressManager.UpdateVale(THD_ID);
                }
            }
            
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            string filePath = this.tbFilePath.Text;
            string shtName = this.cbbShtName.Text;
            ImportThreadParameter thdParam = new ImportThreadParameter();
            thdParam.FilePath = this.tbFilePath.Text;
            thdParam.SheetName = shtName;
            if (!ValidateCheck(thdParam))
            {
                return;
            }
            if (!File.Exists(filePath))
            {
                Msg("文件不存在！");
                return;
            }

            IsImportErr = false;
            ProgressManager.StartThread(ImportData,(object)thdParam);
            if (!IsImportErr)
            {
                Msg("导入数据成功");
                CloseFrm();
            }
            else
            {
                Msg("导入数据失败");
            }
        }
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="thdParam"></param>
        private void ImportData(object thdParam)
        {
            ImportThreadParameter param = (ImportThreadParameter)thdParam;
            try
            {
                IsImportData = true;
                if (param.FileType == DataFileType.Excel)
                {
                    ImportExcelData(param.FilePath, param.SheetName);
                }
                else
                {
                    ImportTextData(param.FilePath);
                }
                
                GC.Collect();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                IsImportErr = true;
            }
            if (IsImportData)
            {
                IsImportData = !IsImportErr;
            }
            ProgressManager.CloseProcessFrm();
        }
        /// <summary>
        /// 有效性检测
        /// </summary>
        /// <param name="thdParam"></param>
        /// <returns></returns>
        private bool ValidateCheck(ImportThreadParameter thdParam)
        {
            if (!File.Exists(thdParam.FilePath))
            {
                Msg("文件不存在！");
                return false;
            }
            if (Path.GetExtension(thdParam.FilePath).ToLower() != ".txt")
            {
                if (thdParam.SheetName == "")
                {
                    Msg("请填写工作表名称");
                    return false ;
                }
            }
            return true;
        }
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx|文本文档(*.txt)|*.txt";
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                this.tbFilePath.Text = ofd.FileName;
            }
        }
        private void tbFilePath_TextChanged(object sender, EventArgs e)
        {
            string filePath = ((TextBox)sender).Text.ToLower();
            string ExtName = Path.GetExtension(filePath);
            bool bVisible = (ExtName == ".xls")||(ExtName == ".xlsx");
            if (bVisible)
            {
                this.cbbShtName.DataSource = Funcs.GetSheetNamesFromWorkbook(filePath);
            }
            this.LabTableName.Visible = bVisible;
            this.cbbShtName.Visible = bVisible;

        }
        private void InitExampleDT()
        {
            dtExample = new DataTable();
            dtExample.Columns.Add("序号", typeof(string));
            dtExample.Columns.Add("姓名", typeof(string));
            dtExample.Columns.Add("生日", typeof(string));
            dtExample.Columns.Add("阴阳历", typeof(string));
            dtExample.Columns.Add("手机", typeof(string));
            dtExample.Rows.Add();
            dtExample.Rows[0][0] = 1;
            dtExample.Rows[0][1] = "我是菜鸟";
            dtExample.Rows[0][2] = "1988-7-15";
            dtExample.Rows[0][3] = "阳历";
            dtExample.Rows[0][4] = "12345678910";
            this.dgvExample.DataSource = dtExample;
            int colWidth;
            for (int colIdx = 0; colIdx < dgvExample.Columns.Count; colIdx++)
            {
                if(colIdx == 0)
                {
                    colWidth = 45;
                }
                else if (colIdx == 4)
                {
                    colWidth = 80;
                }
                else
                {
                    colWidth = 65;
                }
                dgvExample.Columns[colIdx].Width = colWidth;
                dgvExample.Columns[colIdx].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
        }
        private void tbTableName_TextChanged(object sender, EventArgs e)
        {
            Cfg.WriteConfig(GlobalValue.SFT_CFG, GlobalValue.SFT_CFG_IMPORT_SHT_NAME, ((TextBox)sender).Text);
        }
        /// <summary>
        /// 关闭窗口委托
        /// </summary>
        private delegate void dl_CloseFrm();
        /// <summary>
        /// 关闭窗口
        /// </summary>
        private void CloseFrm()
        {
            if (this.InvokeRequired)
            {
                dl_CloseFrm method = CloseFrm;
                Invoke(method);
                return;
            }
            this.Close();
        }
        private delegate DialogResult dl_Msg(string str, MessageBoxButtons btn);
        /// <summary>
        /// 消息显示
        /// </summary>
        /// <param name="str">消息内容</param>
        /// <param name="btn">按钮类型</param>
        /// <returns>消息窗体结果</returns>
        private DialogResult Msg(string str, MessageBoxButtons btn = MessageBoxButtons.OK)
        {
            if (this.InvokeRequired)
            {
                dl_Msg method = Msg;
                return (DialogResult)Invoke(method, str, btn);
            }
            return MessageBox.Show(str, "提醒", btn);
        }
    }
    enum DataFileType
    {
        Excel,
        Txt,
    }
    /// <summary>
    /// 线程参数
    /// </summary>
    class ImportThreadParameter
    {
        string _FilePath;
        public string FilePath 
        {
            get
            { 
                return _FilePath;
            }
            set 
            { 
                _FilePath = value;
                if (Path.GetExtension(_FilePath).ToLower() == ".txt")
                {
                    FileType = DataFileType.Txt;
                }
                else
                {
                    FileType = DataFileType.Excel;
                }
            }
        }
        public string SheetName { get; set; }
        public DataFileType FileType { get; set; }
    }
}
